package com.hong.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.hong.springboot.netty.WebSocketClientHandler;
import com.hong.springboot.netty.WebsocketClient;
import com.hong.springboot.utils.DataResponse;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: csh
 * @Date: 2020/8/18 16:11
 * @Description:
 */
@RestController
@RequestMapping("/")
@Log4j2
public class UserController {

    @Autowired
    private WebsocketClient websocketClient;


    @RequestMapping(value = "",method = RequestMethod.GET)
    @ResponseBody
    public DataResponse<Boolean> sendMsg(String msg){
        try {
            log.info("请求进来了{}",msg);
            Channel channel = websocketClient.getChannel();
            log.info("获取的channel"+ JSONObject.toJSONString(channel));
            WebSocketFrame frame = new TextWebSocketFrame(msg);
            channel.writeAndFlush(frame);
            return DataResponse.BuildSuccessResponse();
        }catch (Exception e){
            log.error("发送出错!{}",e);
        }
        return DataResponse.BuildFailResponse("发送出错！");
    }

    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @ResponseBody
    public DataResponse<Boolean> user(Integer id){
        try {
            WebSocketClientHandler handler = websocketClient.getHandler();
            String method = "com.hong.spring.service.IUserService.findById"+"#"+id;
            handler.setParam(method);
            handler.call();
            log.info("获取的channel"+ JSONObject.toJSONString(handler.getResult()));
            return DataResponse.BuildSuccessResponse(handler.getResult());
        }catch (Exception e){
            log.error("发送出错!{}",e);
        }
        return DataResponse.BuildFailResponse("发送出错！");
    }
}
